/*
	This file is part of AVRCppLib.

    AVRCppLib is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    AVRCppLib is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with AVRCppLib.  If not, see <http://www.gnu.org/licenses/>.

    Copyright (C) Maxime Lemonnier 2007-2011
 */

#include "stdioUSART.h"

namespace Coms
{
namespace USART
{

FILE* fdevopen(uint8_t mode, USARTHardware * usartHardware)
{
	FILE * stream = new FILE();


	if(mode & _FDEV_SETUP_WRITE)
	{
		usartHardware->enableTransmitter();
		stream->put = put_char;
	}

	if(mode & _FDEV_SETUP_READ)
	{
		usartHardware->enableReceiver();
		stream->get = get_char;
	}

	stream->flags = mode;

	stream->udata = usartHardware;

	return stream;
}


void fdevclose(uint8_t mode, FILE * stream)
{
	USARTHardware * usartHardware = (USARTHardware *)stream->udata;

	if(mode & _FDEV_SETUP_WRITE)
	{
		usartHardware->disableTransmitter();
		stream->put = NULL;

		stream->flags &= ~_FDEV_SETUP_WRITE;
	}

	if(mode & _FDEV_SETUP_READ)
	{
		usartHardware->disableReceiver();
		stream->get = NULL;

		stream->flags &= ~_FDEV_SETUP_READ;
	}

	if(!stream->flags)
	{
		delete stream;
	}
}


int put_char(char c, FILE* stream)
{
	USARTHardware * usartHardware = (USARTHardware *)stream->udata;

	while(!usartHardware->isTransmitterReady());

	usartHardware->writeFrame(c);

	return 0;
}

int get_char(FILE* stream)
{
	USARTHardware * usartHardware = (USARTHardware *)stream->udata;

	while(!usartHardware->isFrameReceived());

	return usartHardware->readFrame();
}

}

}

